﻿using System;
using System.Collections;
using System.Data;
using System.Drawing;
using System.Text;
using System.Web.UI;
using System.Web.UI.WebControls;
using Model;

public partial class Administration_Categories : Page
{
    protected Categories current;

    protected void Page_Load(object sender, EventArgs e)
    {
        litTitle.Text = "Administrare categorii";
        if (!string.IsNullOrEmpty(Request.QueryString["ID"]))
        {
            try
            {
                if (!Page.IsPostBack)
                {
                    BindCurrentCategory();
                }
            }
            catch (Exception ex)
            {
                litMessage.Text = ex.Message;
            }
        }
        else
        {
            litMessage.Text = "Selectati categoria dorita pentru a-i edita proprietatile sau pentru a-i administra articolele.";
            dlSubCategories.DataSource = Entities.GetCategories(0);
        }
        if (!Page.IsPostBack)
        {
            dlSubCategories.DataBind();
            if (dlSubCategories.Items.Count > 0 && current != null) dlSubCategories.ShowHeader = true;
        }

        ContentPlaceHolder RightContentHolder = (ContentPlaceHolder)Master.FindControl("RightContentHolder");
        RightContentHolder.Visible = false;
    }
    private void RecursiveFillTree(DataTable dtParent, int parentID, int level)
    {
        level++; //on the each call level increment 1
        System.Text.StringBuilder appender = new System.Text.StringBuilder();

        for (int j = 0; j < level; j++)
        {
            appender.Append("&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;|");
        }
        if (level > 0)
        {
            appender.Append("_ ");
        }

        current = (Categories)ViewState["Category"];
        if (parentID != current.CategoryID)
        {
            DataView dv = new DataView(dtParent);

            dv.RowFilter = string.Format("pid = {0}", parentID);

            int i;

            if (dv.Count > 0)
            {
                for (i = 0; i < dv.Count; i++)
                {
                    if (dv[i]["id"].ToString() != current.CategoryID.ToString())
                    {
                        ddlParentCateg.Items.Add(new ListItem(Server.HtmlDecode(appender.ToString() + dv[i]["Title"].ToString()), dv[i]["id"].ToString()));
                        RecursiveFillTree(dtParent, int.Parse(dv[i]["id"].ToString()), level);
                    }
                }
            }
            level--; //on the each function end level will decrement by 1
        }
    }
    protected void dlSubCategories_ItemDataBound(object sender, DataListItemEventArgs e)
    {
        if (e.Item.ItemType == ListItemType.AlternatingItem || e.Item.ItemType == ListItemType.Item)
        {
            Repeater subsubCategories = (Repeater)e.Item.FindControl("subsubCategories");
            subsubCategories.DataSource = Entities.GetCategories(((Categories)e.Item.DataItem).CategoryID);
            subsubCategories.DataBind();
        }
    }
    protected string LoadNavigation(Categories categ)
    {
        StringBuilder sb = new StringBuilder();

        Categories current = categ;
        ArrayList nav = new ArrayList();
        nav.Add(current);
        while (current.Parent.CategoryID != 0)
        {
            try
            {
                current = current.Parent;
                nav.Add(current);
            }
            catch { break; }
        }
        for (int i = nav.Count - 1; i >= 0; i--)
        {
            Categories x = (Categories)nav[i];
            if (categ.CategoryID != Convert.ToInt32(x.CategoryID))
                sb.Append(@" » <a href=""categories.aspx?ID=" + x.CategoryID + @""">" + x.Title + @"</a>");
            else
                sb.Append(@" » " + x.Title);
        }
        return sb.ToString();
    }
    protected void BindCurrentCategory()
    {
        current = Entities.GetCategoryDetails(Convert.ToInt32(Request.QueryString["ID"]));
        litNav.Text = LoadNavigation(current);
        dlSubCategories.DataSource = Entities.GetCategories(current.CategoryID);
        txtTitle.Text = current.Title;
        htmlDescription.Content = current.Description;
        htmlDescription.DesignPanelCssPath = Utils.GetApplicationSetting(Constants.STYLE_CSS_URL);
        htmlDescription.DocumentCssPath = Utils.GetApplicationSetting(Constants.STYLE_CSS_URL);
        txtWebDesc.Text = current.MetaDesc;
        txtKeys.Text = current.MetaKeys;
        chApproved.Checked = current.Approved;

        if (!string.IsNullOrEmpty(current.ImagePath))
        {
            Bitmap img = new Bitmap(Utils.GetApplicationSetting(Constants.IMAGES_CATEGORIES_PHYSICAL_PATH) + current.ImagePath);
            if (img.Width > img.Height) imgCateg.Width = new Unit(250);
            else imgCateg.Height = new Unit(250);
            imgCateg.ImageUrl = Utils.GetApplicationSetting(Constants.IMAGES_CATEGORIES_URL_PREFIX) + current.ImagePath;
        }
        else
            imgCateg.ImageUrl = Utils.GetApplicationSetting(Constants.IMAGES_CATEGORIES_URL_PREFIX) + Constants.NO_IMAGE_FILE_NAME;

        litTitle.Text = current.Title;
        pnlEdit.Visible = true;
        txtSearch.Visible = false;
        btnSearch.Visible = false;
        ViewState["Category"] = current;
        ViewState["CategoryID"] = current.CategoryID;

        // parent category dropdown binder
        DataTable dt = Entities.GetTreeCategories();
        ddlParentCateg.Items.Clear();
        int level = 0;
        RecursiveFillTree(dt, 0, level);
        ddlParentCateg.Items.Insert(0, new ListItem("Primul nivel", "0"));
        ddlParentCateg.SelectedValue = current.Parent.CategoryID.ToString();

        // bind menu ordinal
        Categories[] menuCategs = Entities.GetCategories(0);
        for (int i = 0; i < menuCategs.Length; i++)
            ddlMenuOrdinal.Items.Add(i.ToString());
        ddlMenuOrdinal.DataBind();
        if (current.MenuOrdinal.HasValue)
            ddlMenuOrdinal.SelectedValue = current.MenuOrdinal.Value.ToString();
    }
    protected void btnSearch_Click(object sender, EventArgs e)
    {
        Categories[] categs = Entities.SearchCategories(txtSearch.Text);
        if (categs != null)
            if (categs.Length == 1)
            {
                Response.Redirect("categories.aspx?ID=" + categs[0].CategoryID);
            }
    }
    protected void btnUpdate_Click(object sender, EventArgs e)
    {
        try
        {
            string imageFileName = uplImage.FileName;
            if (!string.IsNullOrEmpty(imageFileName))
            {
                uplImage.SaveAs(Utils.GetApplicationSetting(Constants.IMAGES_CATEGORIES_PHYSICAL_PATH) + uplImage.FileName);
            }

            int? newParentID = null;
            if (!string.IsNullOrEmpty(ddlParentCateg.SelectedItem.Value))
                newParentID = Convert.ToInt32(ddlParentCateg.SelectedValue);

            int? menuOrdinal = null;
            if (newParentID.HasValue)
                if (newParentID.Value == 0)
                    menuOrdinal = Convert.ToInt32(ddlMenuOrdinal.SelectedValue);

            current = Entities.InsertOrUpdateCategory((int)ViewState["CategoryID"], txtTitle.Text, htmlDescription.Content, txtWebDesc.Text, txtKeys.Text, imageFileName, chApproved.Checked, chFeatured.Checked, newParentID, null,menuOrdinal);

            //Entities.InsertOrUpdateCategory((int)ViewState["CategoryID"], txtTitle.Text, htmlDescription.Content, txtWebDesc.Text, txtKeys.Text, imageFileName, chApproved.Checked, Convert.ToInt32(treeMyTree.GetSelectedItem().id), null);
            litMessage.Text = "Modificarile au fost efectuate cu succes!";
            BindCurrentCategory();
        }
        catch (Exception ex) { litMessage.Text = ex.ToString(); }
    }

    [System.Web.Services.WebMethodAttribute(), System.Web.Script.Services.ScriptMethodAttribute()]
    public static object[] GetCompletionList(string prefixText, int count, string contextKey)
    {
        Categories[] categs = Entities.SearchCategories(prefixText);
        ArrayList s = new ArrayList();
        foreach (Categories categ in categs)
        {
            s.Add(categ.Title);
        }
        return s.ToArray();
    }
}
